package com.mishow.request.listener;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.core.Response;
import com.mishow.volley.http.RequestManager;
/**
 * 作者：wei.miao <br/>
 * 描述：所有接口请求监听
 */
public abstract class OnResponseListener<T> implements Listener<T>, ErrorListener {

	public static final String ERROR_CODE_SYSTEM = "1001";
	
	private Context mContext;
	private SharedPreferencesUtil sp;
	
	public OnResponseListener(Context context) {
		mContext = context;
		sp = new SharedPreferencesUtil(context);
	}
	
	@Override
	public void onResponse(T response) {
		Response resp = changeToResponse(response);
		String code = resp.getBody().getCode();
		if ("000000".equals(code)) {
			
			onSuccess(response);
			
		} else {
			String message = resp.getBody().getMessage();
			onError(code, message);
		}
		onCompleted();
	}
	
	@Override
	public void onErrorResponse(VolleyError error) {
		String message = RequestManager.getInstance().getMessage(error);
		onError(ERROR_CODE_SYSTEM, message);
		onCompleted();
	}
	
	private Response changeToResponse(T response) {
		Response resp = null;
		if (response instanceof Response) {
			resp = (Response) response;
		} else if (response instanceof String) {
			resp = JSON.parseObject((String) response, Response.class);
		} else if (response instanceof org.json.JSONObject) {
			org.json.JSONObject jsonObj = (org.json.JSONObject) response;
			resp = JSON.parseObject(jsonObj.toString(), Response.class);
		}
		return resp;
	}
	
	public abstract void onSuccess(T response);
	
	public abstract void onError(String code, String message);
	
	public abstract void onCompleted();

}
